<?php

namespace addons\order\user\controller;


class RechargeOrder extends \web\user\controller\AddonUserBase {

    public function index() {
        $status = $this->_get('status');
        if ($status == '') {
            $status = 0;
        }
        $this->assign('status', $status);
        return $this->fetch();
    }

    public function loadList() {
        $keyword = $this->_get('keyword');
        $status = $this->_get('status');
        $filter = 'status=' . $status;
        if ($keyword != null) {
            $filter .= ' and username like \'%' . $keyword . '%\'';
        }
        $r = new \addons\order\model\RechargeModel();
        $total = $r->getTotal($filter);
        $rows = $r->getList($this->getPageIndex(), $this->getPageSize(), $filter,'update_time desc');
        $count_total = $r->getCountTotal($filter);
        return $this->toTotalDataGrid($total, $rows,$count_total);
    }

    //查看图片
    public function show_pic() {
        $id = $this->_get('id');
        $m = new \addons\order\model\RechargeModel();
        $data = $m->getPicById($id);
        $pic = $data['pic'];
        $this->assign('pic', $pic);
        return $this->fetch();
    }

    //审核
    public function doCheck() {
        $orderId = $this->_get('id');
        $state = $this->_get('status');
        $rechargeM = new \addons\order\model\RechargeModel();
        $balanceM = new \addons\member\model\Balance();
        $recordM = new \addons\member\model\TradingRecord();
        $orderData = $rechargeM->where(['id' => $orderId])->find();
        $balanceM->startTrans();
        try {
            if ($state == 1) {
                //更新用户余额
                $balanceM->updateBalance($orderData['user_id'], 1, $orderData['amount'], true);
                //获取用户更新完余额
                $balanceData = $balanceM->getBalanceByType($orderData['user_id'], 1);
                $recordM->addRecord($orderData['user_id'], $orderData['amount'], $balanceData['before_amount'], $balanceData['amount'], 1, 8, 1, 0, '充值');
                //修改订单状态
                $rechargeM->where(['id' => $orderId])->update(['status' => 1, 'update_time' => NOW_DATETIME]);
                $balanceM->commit();
                //添加管理日志
                $this->addLog(self::LOG_APPR,'充值订单审核',$_GET, $orderData['user_id']);
                return $this->successData();
            } else {
                //修改订单状态
                $rechargeM->where(['id' => $orderId])->update(['status' => -1, 'update_time' => NOW_DATETIME]);
                $balanceM->commit();
                //添加管理日志
                $this->addLog(self::LOG_CANCEL_APPR,'充值订单反审核',$_GET, $orderData['user_id']);
                return $this->successData();
            }
        } catch (\Exception $ex) {
            $balanceM->rollback();
            return $this->failData($ex->getMessage());
        }
    }

}
